﻿using System;
using System.Windows.Controls;
using System.Windows.Navigation;
using OFX.Aggregator.Infrastructure;
using NavigationEventArgs=System.Windows.Navigation.NavigationEventArgs;

namespace OFX.Aggregator.WpfApplication
{
	/// <summary>
	/// Interaction logic for ErrorReportPage.xaml
	/// </summary>
	public partial class ErrorReportPage : Page
	{
		private readonly IIoCContainerAbstraction container;

		public ErrorReportPage(Exception exception, IIoCContainerAbstraction container)
		{
			this.container = container;
			ErrorMessage = getInnermostException(exception).Message;

			InitializeComponent();
		}

		private static Exception getInnermostException(Exception ex)
		{
			if (ex != null)
			{
				while (ex.InnerException != null)
					ex = ex.InnerException;
			}

			return ex;
		}

		public string ErrorMessage { get; set; }

		private void buttonOK_Click(object sender, System.Windows.RoutedEventArgs e)
		{
			NavigationService.RemoveBackEntry();

			var page = this.container.Resolve<Page>("StatementSourceListPage");
			NavigationService.Navigate(page);
			NavigationService.Navigated += NavigationService_Navigated;
		}

		private static void NavigationService_Navigated(object sender, NavigationEventArgs e)
		{
			NavigationService navigationService = ((Page)e.Content).NavigationService;

			navigationService.Navigated -= NavigationService_Navigated;

			navigationService.RemoveBackEntry();
		}
	}
}
